package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.framework.web.domain.CustomerTreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.vo.CustomerVo;
import com.ruoyi.system.domain.vo.StoreVo;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysCustomerMapper;
import com.ruoyi.system.domain.SysCustomer;
import com.ruoyi.system.service.ISysCustomerService;
import com.ruoyi.common.utils.StringUtils;

/**
 * 经销商档案Service业务层处理
 *
 * @author anan
 * @date 2021-03-02
 */
@Service
public class SysCustomerServiceImpl extends ServiceImpl<SysCustomerMapper,CustomerVo> implements ISysCustomerService
{
    @Autowired
    private SysCustomerMapper customerMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 查询经销商档案
     *
     * @param id 经销商档案ID
     * @return 经销商档案
     */
    @Override
    public SysCustomer selectSysCustomerById(Long id)
    {
        return customerMapper.selectSysCustomerById(id);
    }

    /**
     * 查询经销商档案列表
     *
     * @param sysCustomer 经销商档案
     * @return 经销商档案
     */
    @Override
    public List<SysCustomer> selectSysCustomerList(SysCustomer sysCustomer)
    {
        return customerMapper.selectSysCustomerList(sysCustomer);
    }

    /**
     * 查询经销商档案列表
     *
     * @param sysCustomer 经销商档案
     * @return 经销商档案
     */
    @Override
    public List<CustomerVo> selectCustomerList(CustomerVo sysCustomer)
    {
        return customerMapper.selectCustomerList(sysCustomer);
    }

    /**
     * 新增经销商档案
     *
     * @param sysCustomer 经销商档案
     * @return 结果
     */
    @Override
    public int insertSysCustomer(SysCustomer sysCustomer)
    {
        return customerMapper.insertSysCustomer(sysCustomer);
    }

    /**
     * 修改经销商档案
     *
     * @param sysCustomer 经销商档案
     * @return 结果
     */
    @Override
    public int updateSysCustomer(SysCustomer sysCustomer)
    {
        return customerMapper.updateSysCustomer(sysCustomer);
    }

    /**
     * 批量删除经销商档案
     *
     * @param ids 需要删除的经销商档案ID
     * @return 结果
     */
    @Override
    public int deleteSysCustomerByIds(Long[] ids)
    {
        return customerMapper.deleteSysCustomerByIds(ids);
    }

    /**
     * 删除经销商档案信息
     *
     * @param id 经销商档案ID
     * @return 结果
     */
    @Override
    public int deleteSysCustomerById(Long id)
    {
        return customerMapper.deleteSysCustomerById(id);
    }

    /**
     * @param roleId
     * @return
     */
    @Override
    public List<SysCustomer> roleCustomerTreeselect(Long roleId) {
        return customerMapper.roleCustomerTreeselect(roleId);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param customers 经销商列表
     * @return 下拉树结构列表
     */
    @Override
    public List<CustomerTreeSelect> buildCustomerTreeSelect(List<CustomerVo> customers) {
        List<CustomerVo> customerTrees = buildCustomerTree(customers);
        return customerTrees.stream().map(CustomerTreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<Map<String,Object>> selectCustomerListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return customerMapper.selectCustomerListByRoleId(roleId, role.isCustomerCheckStrictly());
    }

    @Override
    public List<Map<String,Object>> selectCustomerListByUserId(Long userId) {
        /** SysUser user = userMapper.selectUserById(userId); */
        return customerMapper.selectCustomerListByUserId(userId);
    }

    @Override
    public List<CustomerVo> conversionList(List<CustomerVo> customers, List<Map<String, Object>> maps, List<StoreVo> storeVos) {
        if (storeVos!=null && storeVos.size() > 0) {
            for (StoreVo storeVo:storeVos) {
                for (CustomerVo customerVo:customers) {
                    if (storeVo.getId().equals(customerVo.getId())) {
                        customerVo.setStoreCount(storeVo.getStoreIds().size());
                        break;
                    }
                }
            }
        }
        if (maps.size() > 0)
        {
            for (int i = 0; i < maps.size(); i++)
            {
                Map<String, Object> map = maps.get(i);
                for (CustomerVo customerVo : customers)
                {
                    if (String.valueOf(map.get("ID")).equals(customerVo.getId().toString()))
                    {
                        customerVo.setCustomerType((String) map.get("PERMISSION_TYPE"));
                        break;
                    }
                }
            }
        }
        return customers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param customers 部门列表
     * @return 树结构列表
     */
    public List<CustomerVo> buildCustomerTree(List<CustomerVo> customers)
    {
        List<CustomerVo> returnList = new ArrayList<CustomerVo>();
        List<Long> tempList = new ArrayList<Long>();
        for (CustomerVo customer : customers)
        {
            tempList.add(customer.getId());
            if (customer.getId()==4295 || customer.getId()==213){
                System.out.println(customer.getId());
            }
        }
        for (Iterator<CustomerVo> iterator = customers.iterator(); iterator.hasNext();)
        {
            CustomerVo customer = (CustomerVo) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
			if (0 == customer.getCCustomerupId())
			{
				recursionFn(customers, customer);
				returnList.add(customer);
				break;
			}
//			if (!tempList.contains(customer.getCCustomerupId()))
//			{
//				recursionFn(customers, customer);
//				returnList.add(customer);
//			}
        }
        if (returnList.isEmpty())
        {
            returnList = customers;
        }
        for (Iterator<CustomerVo> iterator = returnList.get(0).getChildren().iterator(); iterator.hasNext(); )
        {
            CustomerVo customer = (CustomerVo) iterator.next();
            if ("N".equals(customer.getIsOnline())){
                iterator.remove();
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<CustomerVo> list, CustomerVo t)
    {
        // 得到子节点列表
        List<CustomerVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CustomerVo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CustomerVo> getChildList(List<CustomerVo> list, CustomerVo t)
    {
        List<CustomerVo> tlist = new ArrayList<CustomerVo>();
        Iterator<CustomerVo> it = list.iterator();
        while (it.hasNext())
        {
            CustomerVo n = (CustomerVo) it.next();
            if (StringUtils.isNotNull(n.getCCustomerupId()) && n.getCCustomerupId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<CustomerVo> list, CustomerVo t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
